﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using SdmxMl.Common;
using SdmxMl.Helper;
using SdmxMl.Manager;
using SdmxMl.Multiplexor;

namespace SdmxMl.Panels
{
    /// <summary>
    /// Dialog for accessing Web repository information on Artefacts
    /// </summary>
    public partial class DlgGetArtefact : Form
    {
        #region Constants

        const string TABLE_COL_DIFFUSION_CODE = "DI";

        #endregion

        #region Internal Members

        private static DescendantMode lastSelectedMode = DescendantMode.Children;

        public string ArtefactTarget { get; set; }
        public string ArtefactType { get; set; }

        private TreeSdmxManager treeSdmxManager;
        private BindingSource myBindingSource;
        private bool inConstruct;
        private backupVersion versionSelected = null;

        #endregion

        #region Properties

        private SmManager SmMgr;

        #endregion

        #region Constructor

        public DlgGetArtefact(TreeSdmxManager treeSdmxManager)
        {
            InitializeComponent();
            inConstruct = true;

            this.treeSdmxManager = treeSdmxManager;

            buttonGet.Enabled = false;
            buttonDelete.Enabled = false;
            buttonCheckOut.Enabled = false;
            buttonDiffusion.Enabled = false;
            buttonOwner.Enabled = false;

            // Fill combo
            foreach (SdmxArtefactType atype in Enum.GetValues(typeof(SdmxArtefactType)))
                if (atype != SdmxArtefactType.None)
                    comboBoxArtefactType.Items.Add(new ComboArtefactTypeItem(atype));
            comboBoxArtefactType.SelectedItem = comboBoxArtefactType.Items[2]; // Default to codelists

            comboBoxAO1.SelectedIndex = comboBoxAO2.SelectedIndex = comboBoxAO3.SelectedIndex = 0;

            // Fill importMode
            foreach (DescendantMode md in Enum.GetValues(typeof(DescendantMode)))
                comboBoxModeImport.Items.Add(md);
            comboBoxModeImport.SelectedItem = lastSelectedMode;

            InitRegistryProxy();
            dataGridViewList.Columns["ColumnOwner"].Visible = Mux.IsNewSmsRegistry;
            inConstruct = false;

            // Display default artefact selection content (old SMS only)
            if (buttonList.Enabled && Mux.IsNewSmsRegistry == false)
                buttonList_Click(this, EventArgs.Empty);

            
        }

        private void InitRegistryProxy()
        {
            using (new SdmxMl.Helper.CWaitCursor())
            {
                this.Text = "Get Artefact from SMS - " + Mux.Instance.DirInfoRegistryAlias;
                textBoxAgencyId.Text = Mux.Instance.DirInfoAgencyFilter;
            }
        }
        #endregion

        #region Datagrid Completed Event

        /// <summary> Uses event to define image for diffusion status & aggregation </summary>
        /// <param name="sender"></param><param name="e"></param>
        private void dataGridViewList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < dataGridViewList.Rows.Count; i++)
            {
                int index = Convert.ToInt32(dataGridViewList.Rows[i].Cells["ColumnDiffNum"].Value);
                if (dataGridViewList.Rows[i].Cells["ColumnDiff"].Value == null)
                    dataGridViewList.Rows[i].Cells["ColumnDiff"].Value = imageListDiff.Images[index];
                //if (dataGridViewList.Rows[i].Cells["ColumnAG"].Value != DBNull.Value &&
                //    Convert.ToBoolean(dataGridViewList.Rows[i].Cells["ColumnAG"].Value) == true)
                if (dataGridViewList.Rows[i].Cells["ColumnCB"].Value != DBNull.Value &&
                    dataGridViewList.Rows[i].Cells["ColumnCB"].Value.ToString() != string.Empty)
                    dataGridViewList.Rows[i].Cells["ColumnAGimg"].Value = imageListDiff.Images[6];
                else
                    dataGridViewList.Rows[i].Cells["ColumnAGimg"].Value = imageListDiff.Images[5];
            }
        }
        #endregion

        #region Image sorting (checkout info as image)

        private SortOrder _sortDirection = SortOrder.Ascending;
        /// <summary>
        /// Catch column header click Event and proceed a programmatic sort for image column
        /// based on checkout column information
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void dataGridViewList_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                // Check for targeted column & information present
                if (e.ColumnIndex == 0 && myBindingSource.DataSource != null)
                {
                    string sort = string.Empty;
                    switch (_sortDirection)
                    {
                        case SortOrder.None:
                        case SortOrder.Descending:
                            _sortDirection = SortOrder.Ascending;
                            sort = "asc";
                            break;
                        case SortOrder.Ascending:
                            _sortDirection = SortOrder.Descending;
                            sort = "desc";
                            break;
                    }

                    // image for sort direction
                    dataGridViewList.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = _sortDirection;
                    if (!string.IsNullOrEmpty(sort))
                    {
                        myBindingSource.Sort = "CO " + sort; // sort on column checked out by
                    }
                    else
                    {
                        myBindingSource.RemoveSort();
                    }
                }
            }
            catch { }
        }
        #endregion

        #region Binding Filter on list of artefacts

        /// <summary> Reset binding filter edit controls </summary>
        private void ClearFiltering()
        {
            if (textBoxAgencyId.Text.Length == 0)
                textBoxAgencyId.Text = Mux.Instance.DirInfoAgencyFilter;

            //textBoxId.Text = string.Empty;
            //textBoxName.Text = string.Empty;
            //textBoxVersion.Text = string.Empty;
        }

        //First of all let us say that all expressions used to filter data have string as format
        //If the member type is string you must wrap the criteria value in quotation marks like this sample : "ProductID = 'PR0001k12'" 
        //If the member type is number you can write the expression like this "Maximum = 50" 
        //If the member has a name composed by two or more words that are separated by space, in a such case, you must wrap it in brakets [ ] like this sample: "[First Name] = 'Dihia' "
        //If the member has a name that contains one of those characters \n (newline) \t (tab) \r (carriage return) ~ ( ) # \ / = > < + - * % & | ^ ' " [ ] 
        //Those symbols are considered as special characters, so you must another once, as the example above I mean the third remark, wrap it in brakets [ ] like this sample: "[FirstName#] = 'Dihia' "
        //If the member name has this format xxx[ ],[ ]xxx or x[ ]xx, because the brakets are used here as special characters, you must use a slash â€˜\' to escape the brakets as follow: "[First Name[\]] = 'Dihia' "
        //If the member type is a date, in this case, you must wrap the criteria value in pound signs # such as "[Date of birth] = #11/04/78# ", the month at first, the day at second and the year at third position.
        // You can combine more than one criteria at once by using AND,OR and NOT key words for example "(Maximum = 50 OR Minimum = 20) AND Weight = 30" 
        //You can use operators like =,<,>,<=,>=,IN,LIKE for example: "(Maximum = 50 OR Minimum > 20) AND [Product Name] LIKE 'Moster' " 
        //The arithmetic operators + - * / % can also be used as follow: "[Reduced Price] =[Original Price] * 1.2 "
        //You can use agregate too, like Sum:Sum,Max:Maximum,Min:Minimum,Avg:Average,Var:Variance ,StDev:Standard deviation as follow "[Estimated Price] = (Price â€“ Avg(Price))/StDev(Price)" if, of Corse, the statistic variable Price follows a stochastic process related to the normal standard Gauss' law.

        private void ConstructBindingFilter()
        {
            myBindingSource = new BindingSource();
            StringBuilder sb = new StringBuilder(256);
            string id = textBoxId.Text.Trim().Replace('*', '%');
            string agency = textBoxAgencyId.Text.Trim().Replace('*', '%');
            string version = textBoxVersion.Text.Trim().Replace('*', '%');
            string name = textBoxName.Text.Trim().Replace('*', '%');

            if (id.Length > 0)
                sb.Append("ID like '").Append(id).Append("'");
            if (agency.Length > 0)
            {
                if (sb.Length > 0)
                    sb.Append(" ").Append(comboBoxAO1.SelectedItem.ToString()).Append(" ");
                sb.Append("AI like '").Append(agency).Append("'");
            }
            if (version.Length > 0)
            {
                if (sb.Length > 0)
                    sb.Append(" ").Append(comboBoxAO2.SelectedItem.ToString()).Append(" ");
                sb.Append("VER like'").Append(version).Append("'");
            }

            if (name.Length > 0)
            {
                if (sb.Length > 0)
                    sb.Append(" ").Append(comboBoxAO3.SelectedItem.ToString()).Append(" ");
                sb.Append("Name_").Append(LangSupport.CurLang).Append(" like'").Append(name).Append("'");
            }
            if (sb.Length > 0)
                myBindingSource.Filter = sb.ToString();
        }
        #endregion

        #region Helper methods

        private SdmxArtefactType GetArtefactType()
        {
            if (comboBoxArtefactType.SelectedItem != null)
                return (comboBoxArtefactType.SelectedItem as ComboArtefactTypeItem).ArType;
            return SdmxArtefactType.None;
        }

        private DataRow FindSelectedRow()
        {
            DataRow findRow = null;
            BindingManagerBase bm = dataGridViewList.BindingContext[dataGridViewList.DataSource, dataGridViewList.DataMember];
            if (bm.Count > 0)
                findRow = ((DataRowView)bm.Current).Row;

            return findRow;
        }

        private string FullIdFromSelectedRow(DataRow findRow)
        {
            StringBuilder sb = new StringBuilder();
            if (findRow != null)
            {
                sb.Append(findRow["AI"].ToString()).Append('+');
                sb.Append(findRow["ID"].ToString()).Append('+');
                sb.Append(findRow["VER"].ToString());
            }


            return sb.ToString();
        }
        #endregion

        #region List Artefacts Event

        /// <summary>Artefact type selection change Event</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void comboBoxArtefactType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!inConstruct)
            {
                ClearFiltering();
                dataGridViewList.Focus();

                // Activate full list
                buttonList_Click(this, EventArgs.Empty);
            }

            //dataGridViewList.DataSource = null;
            //buttonGet.Enabled = false;
        }

        /// <summary>
        /// List information on all artefacts of specified type that are in repository
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void buttonList_Click(object sender, EventArgs e)
        {
            using (SdmxMl.Helper.CWaitCursor w = new SdmxMl.Helper.CWaitCursor())
            {
                try
                {
                    ConstructBindingFilter();
                    if (Mux.Instance.RunningOK == false)
                    {
                        MessageBox.Show("Registry is not ready!", "Error");
                        return;
                    }

                    DataSet ds = Mux.Instance.DirInfoProxy.DirInfo(GetArtefactType().ToString());
                    //    dataGridViewList.Columns["ColumnName"].DataPropertyName = "Name_" + SdmxMl.Common.LangSupport.CurLang;
                    if (ds.Tables.Count > 0)
                    {
                        myBindingSource.DataSource = null;
                        myBindingSource.DataSource = ds;
                        myBindingSource.DataMember = ds.Tables[0].TableName;

                    }
                    else
                        myBindingSource.DataSource = null;

                    dataGridViewList.AutoGenerateColumns = false;
                    dataGridViewList.DataSource = myBindingSource;
                    buttonGet.Enabled = myBindingSource.DataSource != null;

                    StringBuilder sb = new StringBuilder();
                    sb.Append("Availability: ");
                    if (myBindingSource.DataSource == null)
                        sb.Append(0);
                    else
                        sb.Append(myBindingSource.Count.ToString());
                    groupBoxList.Text = sb.ToString();

                    bool enabled = myBindingSource.DataSource != null && myBindingSource.Count > 0;
                    buttonCheckOut.Enabled = enabled;
                    buttonDelete.Enabled = enabled;
                    buttonDiffusion.Enabled = enabled;
                    buttonOwner.Enabled = enabled && Mux.IsNewSmsRegistry;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to execute. " + ex.Message);
                }
            }
        }
        #endregion

        #region Get Artefact event

        /// <summary>Get Artefact via double click on list row</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void dataGridViewList_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0)
                buttonGet_Click(sender, EventArgs.Empty);
        }

        /// <summary> Extends event raised for get artefact </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void buttonGet_Click(object sender, EventArgs e)
        {
            buttonGet_Click(sender,
                e,
                false);
        }

        private bool GetOneSelection(DataRow findRow, bool isBackup)
        {
            bool errorOccured = false;
            try
            {
                string fullId = FullIdFromSelectedRow(findRow);

                SdmxArtefactType aType = GetArtefactType();
                SdmxMl.Common.ArtefactRefTyped art = new SdmxMl.Common.ArtefactRefTyped(aType, fullId);

                // If artefact already in memory ask for refresh
                Artefact aTarget = ReferenceManager.LocateArtefact(GetArtefactType(), art);
                if (aTarget != null)
                {
                    TreeNode targetNode = null;
                    TreeView tv = ReferenceManager.TreeSdmx;
                    if (tv != null)
                    {
                        TreeHelper.LocateObject(tv, aTarget, ref targetNode);
                        if (targetNode != null)
                        {
                            if (MessageBox.Show("Artefact" + aTarget.FullIdent + " is already in memory, refresh it with Repository Version ?", "Repository", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                            {

                                ArtefactManager arm = targetNode.Parent.Tag as ArtefactManager;
                                if (arm != null)
                                {
                                    targetNode.Parent.Nodes.Remove(targetNode);
                                    arm.ArtefactList.Remove(aTarget);
                                }
                            }
                        }
                    }
                }

                XmlDocument xDoc = new XmlDocument();
                if (SmMgr == null)
                    SmMgr = new SmManager();

                if (Mux.Instance.DirInfoProxy.Version >= 1 && isBackup)
                {
                    xDoc = Mux.Instance.DirInfoProxy.GetArtefactBackup(GetArtefactType().ToString(), fullId, versionSelected.Version);
                    SmMgr.LoadSdmxDocument(null, true, xDoc);
                }
                else
                {
                    xDoc = Mux.Instance.DirInfoProxy.GetArtefact(art.Type.ToString(), art.FullIdent);
                    SmMgr.LoadSdmxDocument(null, true, xDoc);
                    if ((DescendantMode)comboBoxModeImport.SelectedItem != DescendantMode.Single)
                    {
                        DescendantMgr desMgr = new DescendantMgr(SmMgr, art, (DescendantMode)comboBoxModeImport.SelectedItem);
                        desMgr.Explore();

                        SmMgr = desMgr.SmContainer;
                    }
                }

                if (treeSdmxManager != null)
                {
                    object ob = NavigationManager.LoadFromSmManager(SmMgr);
                    NavigationManager.RequestNavigation(ob);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                errorOccured = true;
            }
            return errorOccured;
        }

        /// <summary> Extends event raised for get artefact </summary>
        /// <param name="sender"></param> <param name="e"></param>
        /// <param name="isBackup">Do we treat a backuped previous instance of artefact selected</param>
        private void buttonGet_Click(object sender, EventArgs e, bool isBackup)
        {
            using (new Helper.CWaitCursor())
            {
                // test multi
                if (dataGridViewList.SelectedRows != null && dataGridViewList.SelectedRows.Count > 0)
                {
                    SmMgr = null; // Reset container

                    foreach (DataGridViewRow fr in dataGridViewList.SelectedRows)
                    {

                        DataRowView drv = fr.DataBoundItem as DataRowView;
                        DataRow findRow = drv != null ? drv.Row : null;
                        if (GetOneSelection(findRow, isBackup))
                            break;
                    }
                }
            }
        }
        #endregion

        #region CheckOut Event

        /// <summary>
        /// Reserves (check out) Artefact in registry and get it in memory
        /// </summary>
        /// <param name="sender"></param><param name="e"></param>
        private void buttonCheckOut_Click(object sender, EventArgs e)
        {
            using (new Helper.CWaitCursor())
            {
                try
                {
                    if (dataGridViewList.SelectedRows != null && dataGridViewList.SelectedRows.Count > 0)
                    {
                        SmMgr = null; // Reset
                        foreach (DataGridViewRow fr in dataGridViewList.SelectedRows)
                        {

                            DataRowView drv = fr.DataBoundItem as DataRowView;
                            DataRow findRow = drv != null ? drv.Row : null;
                            bool errorOccured = false;

                            if (findRow != null)
                            {
                                // Process checkout request
                                string fullId = FullIdFromSelectedRow(findRow);
                                Mux.Instance.DirInfoProxy.CheckOut(GetArtefactType().ToString(), fullId);

                                // Update grid
                                findRow["CO"] = Mux.Instance.UserId;
                                findRow["CA"] = DateTime.Now.ToString("yyyy.MM.dd");

                                // And get it in memory
                                errorOccured = GetOneSelection(findRow, false);

                                // Before to ensure main tree updates of the selection
                                Application.DoEvents();

                                // Refresh Tree icon
                                if (treeSdmxManager != null && treeSdmxManager.TV != null &&
                                    treeSdmxManager.TV.SelectedNode != null &&
                                    treeSdmxManager.TV.SelectedNode.Tag is Artefact)
                                {
                                    Artefact a = treeSdmxManager.TV.SelectedNode.Tag as Artefact;
                                    a.RegCheckState = CheckInOutState.CheckOut;
                                    treeSdmxManager.TV.SelectedNode.ImageIndex
                                        = treeSdmxManager.TV.SelectedNode.SelectedImageIndex = 18;
                                }

                                if (errorOccured)
                                    break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
        }
        #endregion

        #region Delete Artefact Event

        /// <summary>
        /// Delete selected artefact from Repository content
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridViewList.SelectedRows != null && dataGridViewList.SelectedRows.Count > 0)
                {
                    foreach (DataGridViewRow fr in dataGridViewList.SelectedRows)
                    {
                        DataRowView drv = fr.DataBoundItem as DataRowView;
                        DataRow findRow = drv != null ? drv.Row : null;
                        if (findRow != null && myBindingSource != null)
                        {
                            // Temp, check that if artefact is Final only administrator can delete it (will be included in Repository web service)
                            if (findRow["IF"].ToString().ToLower() == "true" && Mux.Instance.UserIsAdmin == false)
                            {
                                MessageBox.Show(string.Format("Artefact {0} is finalized. Only Administrator is allowed to delete it!.", findRow["Id"].ToString()), "Caution", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            }
                            else
                            {
                                DialogResult dlgResult =
                                MessageBox.Show("Delete Artefact " + findRow["Id"].ToString() + " Version " + findRow["Ver"].ToString() + "?", "Check",
                                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                if (dlgResult == DialogResult.Cancel)
                                    break;

                                if (dlgResult == DialogResult.Yes)
                                {
                                    DataSet ds = myBindingSource.DataSource as DataSet;
                                    if (ds != null && ds.Tables.Count > 0)
                                    {
                                        string fullId = FullIdFromSelectedRow(findRow);
                                        Mux.Instance.DirInfoProxy.DeleteArtefact(GetArtefactType().ToString(), fullId);
                                        ds.Tables[0].Rows.Remove(findRow);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
        #endregion

        #region Set Diffusion Status event

        /// <summary>Defines diffusion status Event</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void buttonDiffusion_Click(object sender, EventArgs e)
        {
            bool operated = false;
            try
            {
                if (dataGridViewList.SelectedRows != null && dataGridViewList.SelectedRows.Count > 0)
                {
                    string newState = string.Empty;
                    foreach (DataGridViewRow fr in dataGridViewList.SelectedRows)
                    {

                        DataRowView drv = fr.DataBoundItem as DataRowView;
                        DataRow findRow = drv != null ? drv.Row : null;

                        if (findRow != null && myBindingSource != null)
                        {
                            if (newState == string.Empty)
                            {
                                int index = Convert.ToInt32(findRow[TABLE_COL_DIFFUSION_CODE]);
                                DlgDiffusionStatus dlgDiff = new DlgDiffusionStatus(imageListDiff, index);
                                if (dlgDiff.ShowDialog() == DialogResult.OK)
                                    newState = dlgDiff.State;
                                else
                                    break;
                            }

                            if (newState.Length > 0)
                            {
                                DataSet ds = myBindingSource.DataSource as DataSet;
                                if (ds != null && ds.Tables.Count > 0)
                                {
                                    operated = true;
                                    string fullId = FullIdFromSelectedRow(findRow);
                                    Mux.Instance.DirInfoProxy.SetDisseminationStatus(GetArtefactType().ToString(), fullId, newState);
                                }
                            }
                        }
                    }
                }
                if (operated)
                    buttonList_Click(this, EventArgs.Empty);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
        #endregion

        #region Define Repository source

        /// <summary> Redefines Repository service URL </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void repositorySourceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string group = ReferenceManager.TreeMgr.RepositorySelect(this);
            InitRegistryProxy();
            textBoxAgencyId.Text = group;

            // Request a new load of currently selected artefact
            if (buttonList.Enabled)
                buttonList_Click(this, EventArgs.Empty);

        }
        #endregion

        #region Backup Information Event

        /// <summary>Datagrid selection changed Event. Refresh backup count </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void dataGridViewList_SelectionChanged(object sender, EventArgs e)
        {
            if (inConstruct == false)
            {
                try
                {
                    // Allows backup access only in single selection mode
                    textBoxBackupCount.Enabled = dataGridViewList.SelectedRows.Count == 1;

                    DataRow findRow = FindSelectedRow();

                    if (Mux.Instance.DirInfoProxy != null && Mux.Instance.DirInfoProxy.Version >= 1 && findRow != null)
                    {
                        string Id = findRow["Id"].ToString();
                        string Version = findRow["Ver"].ToString();
                        string Agency = findRow["AI"].ToString();

                        if (Id.Length > 0 && Version.Length > 0 && Agency.Length >= 0)
                        {
                            // Try to retrieve backup information from WS
                            StringBuilder sb = new StringBuilder();
                            sb.Append(Agency).Append("+").Append(Id).Append("+").Append(Version);
                            SdmxArtefactType arType = GetArtefactType();
                            bool bBackup = Mux.Instance.DirInfoProxy.IsBackupExist(arType.ToString(), sb.ToString());
                            if (bBackup)
                            {
                                // Display a ToolTip with the list of backuped files
                                StringBuilder sbBackupList = new StringBuilder();
                                DataSet dsBackup = Mux.Instance.DirInfoProxy.GetBackupList(arType.ToString(), sb.ToString());
                                DataTable dt = dsBackup.Tables[0];
                                // Sort by version number descending
                                DataView dvBackup = new DataView(dt);
                                dvBackup.Sort = "VERSION_NUMBER DESC";
                                foreach (DataRow currentRow in dvBackup.Table.Rows)
                                {
                                    sbBackupList.Append("Version: ").Append(currentRow["VERSION_NUMBER"].ToString()).Append("  Date: ").Append(currentRow["VERSION_DATE"]).Append("\n");
                                }

                                textBoxBackupCount.Text = dvBackup.Table.Rows.Count.ToString();
                                toolTip1.SetToolTip(textBoxBackupCount, sbBackupList.ToString());
                            }
                            else
                            {
                                toolTip1.SetToolTip(textBoxBackupCount, string.Empty);
                                textBoxBackupCount.Text = "0";
                            }
                        }
                    }
                    else
                    {
                        toolTip1.SetToolTip(textBoxBackupCount, string.Empty);
                        textBoxBackupCount.Text = "0";
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Backup error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>Backup Count click event</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void textBoxBackupCount_Click(object sender, EventArgs e)
        {
            try
            {
                // Only for new version of WS
                if (Mux.Instance.DirInfoProxy != null && Mux.Instance.DirInfoProxy.Version >= 1)
                {
                    if (textBoxBackupCount.Text != "0")
                    {
                        DataRow findRow = FindSelectedRow();
                        if (findRow != null)
                        {
                            DlgBackupArtefact dlgBackup = new DlgBackupArtefact();
                            dlgBackup.ArtefactType = GetArtefactType().ToString();
                            dlgBackup.Id = findRow["Id"].ToString();
                            dlgBackup.Agency = findRow["AI"].ToString();
                            dlgBackup.Version = findRow["Ver"].ToString();
                            dlgBackup.TinyRegistry = Mux.Instance.DirInfoProxy;
                            dlgBackup.GetInformationBackup();
                            if (dlgBackup.ShowDialog() == DialogResult.OK)
                            {
                                // User made a selection. then retrieve it
                                versionSelected = dlgBackup.SelectedBackup;
                                if (versionSelected != null)
                                    buttonGet_Click(sender, e, true);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
        #endregion

        #region DescendantMode event

        private void comboBoxModeImport_SelectedIndexChanged(object sender, EventArgs e)
        {
            lastSelectedMode = (DescendantMode)comboBoxModeImport.SelectedItem;
        }
        #endregion


        private void textBoxId_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyData & (Keys.Shift | Keys.Alt)) == 0)
            {
                switch (e.KeyData & Keys.KeyCode)
                {
                    case Keys.Return:
                        if ((e.KeyData & Keys.Control) == 0)
                        {
                            buttonList_Click(this, EventArgs.Empty);
                        }
                        break;
                }
            }

        }

        #region Define Owner

        private void buttonOwner_Click(object sender, EventArgs e)
        {
            bool operated = false;
            try
            {
                if (dataGridViewList.SelectedRows != null && dataGridViewList.SelectedRows.Count > 0)
                {
                    string ownerId = string.Empty;
                    OwnerGroupHelper helper = new OwnerGroupHelper();
                    foreach (DataGridViewRow fr in dataGridViewList.SelectedRows)
                    {

                        DataRowView drv = fr.DataBoundItem as DataRowView;
                        DataRow findRow = drv != null ? drv.Row : null;

                        if (findRow != null && myBindingSource != null)
                        {
                            if (ownerId == string.Empty)
                            {
                                ownerId = helper.SelectOwner();
                            }

                            if (ownerId.Length > 0)
                            {
                                operated = true;
                                DataSet ds = myBindingSource.DataSource as DataSet;
                                if (ds != null && ds.Tables.Count > 0)
                                {
                                    string fullId = FullIdFromSelectedRow(findRow);
                                    helper.UpdateOwner(GetArtefactType(), fullId, ownerId);
                                }
                            }
                        }
                    }
                }
                if (operated)
                    buttonList_Click(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Owner definition", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }
        #endregion

        private void dataGridViewList_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
        {

            if (e.Column.Name == "")
            {
                
                e.Handled = true;
                e.SortResult = Compare(e.CellValue1, e.CellValue2);
            }
        }
        //Here is my compare function, it simply reverts the normal comparison result
        private int Compare(object o1, object o2)
        {
            return -o1.ToString().CompareTo(o2.ToString());
        }
    }

    #region Combo Item

    /// <summary>
    /// Class to correct some display in combo of artefact types
    /// </summary>
    internal class ComboArtefactTypeItem
    {
        internal SdmxArtefactType ArType { get; private set; }

        internal ComboArtefactTypeItem(SdmxArtefactType aType)
        {
            ArType = aType;
        }

        public override string ToString()
        {
            if (ArType == SdmxArtefactType.None)
                return "All Artefacts";

            if (ArType == SdmxArtefactType.KeyFamilies)
                return "Data Structure Definition";

            if (ArType == SdmxArtefactType.Concepts)
                return "ConceptSchemes";

            return ArType.ToString();
        }
    }
    #endregion

}
